<?php
/**
 * SmsCode.class.php
 * 短信验证码工具
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2017-09-16
 */

namespace Common\Util;
use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms;

class SmsCode {

    /**
     * 验证短信码
     * @param   $mobile
     * @param   $code
     * @return  boolean
     */
    static function verify($mobile, $code){
        if(!$code){
            return false;
        }

        //验证操作
        if(C('APP_STAGE') >= 2){
            return $code == S('sms_code_'.$mobile);
        }

        return true;
    }

    /**
     * 发送验证码
     * @param   $mobile
     * @return  $code
     */
    static function send($mobile){
        $code   = rand(100000, 999999);

        //线上环境执行发送
        if(C('APP_STAGE') >= 2){
            $aliyun    = new Client([
                'accessKeyId'   => C('ALIYUN_MNS.access_key'),
                'accessKeySecret'   => C('ALIYUN_MNS.access_secret')
            ]);
            
            $aliSms     = new SendSms();
            $aliSms->setPhoneNumbers($mobile);
            $aliSms->setSignName('正心源');
            $aliSms->setTemplateCode('SMS_102320007');
            $aliSms->setTemplateParam(['code' => $code]);
            $aliSms->setOutId(date('YmdHis'));

            $aliyun->execute($aliSms);

            //验证码记入缓存
            S('sms_code_'.$mobile, $code, 600);
        }

        return $code;
    }
}